<template>
  <card :showDivider="false">
    <div class="basic-info-wrapper">
      <div class="section-item">
        <div class="section-item-content transform-top">
          <a-descriptions :size="'medium'" :align="{ label: 'right' }">
            <a-descriptions-item label="费用金额">{{ unitVal(feeDetail.totalAmount, '元') }}</a-descriptions-item>
            <a-descriptions-item label="实收金额">{{ unitVal(feeDetail.receivedAmount, '元') }}</a-descriptions-item>
            <a-descriptions-item label="待收金额">{{ unitVal(feeDetail.receivedNotAmount, '元') }}</a-descriptions-item>
            <a-descriptions-item label="实付金额">{{ unitVal(feeDetail.payAmount, '元') }}</a-descriptions-item>
            <a-descriptions-item label="待付金额">{{ unitVal(feeDetail.payNotAmount, '元') }}</a-descriptions-item>
            <template v-if="totalDetailList && totalDetailList.length > 0">
              <template v-for="(item, index) in totalDetailList" :key="index">
                <a-descriptions-item :label="`${item.name}-账单计划总额`">{{ unitVal(item.amount, '元') }}</a-descriptions-item>
                <a-descriptions-item :label="`${item.name}-账单计划待收金额`"
                  >{{ unitVal(item.receivedNotAmount, '元') }}
                </a-descriptions-item>
              </template>
            </template>
          </a-descriptions>
        </div>
      </div>
      <a-divider :margin="16" />
      <!-- 筛选 -->
      <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadCompulsoryData" />
      <div class="cost-button" v-permission="'svms:order:long-order.confirmfee'">
        <div @click="expenses">合并确认</div>
      </div>
      <!-- 表格 -->
      <table-index class="insure-card-table" :table="tableCompulsory" @loadData="loadCompulsoryData">
        <template #selectkey="{ record }">
          <div
            class="check-box"
            v-if="
              record.level == 1 &&
              (record.costType == 10 || record.costType == 20) &&
              (record.feeStatus == 1 || record.feeStatus == 3 || record.feeStatus == 5) &&
              record.feeNameId != 55 &&
              record.feeNameId != 7 &&
              record.feeType != 2
            "
            ><a-checkbox v-model="setValue[record.id]" @change="checkboxChange($event, record.id)"
          /></div>
          <div v-else> </div>
        </template>
        <template #feeNameSort="{ record }">
          <div v-if="record.mtype == 'MENU'" style="margin-left: 0">{{ record.feeName }}</div>
          <div v-if="record.mtype == 'TERM1'" style="margin-left: 20px">{{ record.feeName }}</div>
          <div v-if="record.mtype == 'TERM2'" style="margin-left: 40px">{{ record.feeName }}</div>
        </template>
        <template #expand-icon="{ expanded }">
          <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
          <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
        </template>
        <template #createTime="{ record }">
          <span>{{ record.createTime }}</span>
        </template>
        <template #receivableTime="{ record }">
          <span>{{ record.receivableTime && record.receivableTime.substring(0, 10) }}</span>
        </template>
      </table-index>
    </div>
    <!-- 确认收款 -->
    <orderfee ref="orderfeepage" @feepageConfirm="feepageConfirm" />
    <!-- 修改费用 -->
    <EditFeeModal ref="editFeeModalRef" @ok="feepageConfirm" />
    <!-- 确认违章费用 -->
    <fee ref="feepage" @feepageConfirm="feepageConfirm" />
    <!-- 违章编辑费用 -->
    <violationEditFeeModal ref="violationEditFee" @feepageConfirm="feepageConfirm" />
    <qcode-modal
      v-model:visible="payQCodeModal"
      :details="clickRecord"
      @close="payQCodeClose"
      :qcodeTitle="qcodeTitle"
      :qcodeCfLoading="qcodeCfLoading"
      @confirm="qcodeConfirm"
      :from="qrcodeFrom"
    />
  </card>
</template>

<script setup name="LongOrderCost">
  import qcodeModal from '@/views/confirmFee/modals/qcode-modal.vue'
  import fee from '@/views/confirmFee/violation/index.vue'
  import orderfee from '../../components/order/index.vue'
  import violationEditFeeModal from '@/views/editFee/violation/index.vue'
  import EditFeeModal from '../../components/edit-fee/edit-fee-modal.vue'

  import { unitVal } from '@/utils'
  import { useTable } from '@/hooks/table'
  import { getLongOrderFeeDetail, checkManyToConfirm } from '@/api/order/czsOrder'
  import { ref, onMounted, computed, reactive } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { usePageDict } from '@/hooks/useDict'
  import { cancelPay } from '@/api/common'

  const qrcodeFrom = ref('')
  const qcodeCfLoading = ref(false)
  const qcodeTitle = ref('收款码')
  const payQCodeModal = ref(false)
  const dict = usePageDict('costConfirmDict')
  const editFeeModalRef = ref()
  const violationEditFee = ref()
  const feepage = ref(null)
  const orderfeepage = ref(null)
  const feeDetail = ref({})
  const expensesKeys = ref([]) //合并id
  const totalDetailList = ref([])
  const queryParam = reactive({})
  const clickRecord = ref({})

  // 查询条件
  const searchList = computed(() => {
    return [
      // { label: '费用类型', prop: 'feeType', type: 'a-select', options: dict.orderFeeTypeEnum },
      { label: '收支类型', prop: 'costType', type: 'a-select', options: dict.costTypeEnum },
      { label: '费用状态', prop: 'feeStatus', type: 'a-select', options: dict.orderFeeStatusEnum },
    ]
  })

  const checkboxChange = (e, id) => {
    const index = expensesKeys.value.indexOf(id)
    if (index > -1) {
      expensesKeys.value.splice(index, 1)
    } else {
      expensesKeys.value.push(id)
    }
  }
  const setValue = computed(() => {
    let obj = {}
    expensesKeys.value.forEach((it) => {
      obj[it] = true
    })
    return obj
  })
  const props = defineProps({
    orderId: Number,
  })
  // 字段处理
  const tabletolist = (list) => {
    list.forEach((el) => {
      el.mtype = 'MENU'
      el.level = 1
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          if (pl.type == 0) {
            pl.feeName = pl.feeCategoryName
            pl.totalAmount = pl.amount
            pl.feeTypeName = pl.feeTypeName
            pl.costTypeName = pl.costType == '10' ? '收款' : '付款'
          }
          if (pl.type == 1) {
            pl.feeName = pl.itemName
            pl.totalAmount = pl.amount
            pl.feeTypeName = pl.feeTypeName
            pl.costTypeName = pl.costType == '10' ? '收款' : '付款'
          }
          if (pl.childrenList && pl.childrenList.length) {
            pl.children = pl.childrenList
            pl.children.forEach((ol) => {
              ol.id = ol.id + 60000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
              ol.mtype = 'TERM2'
              ol.expand = null
              ol.feeName = ol.itemName
              ol.totalAmount = ol.amount
              ol.feeTypeName = ol.feeTypeName
              ol.costTypeName = ol.costType == '10' ? '收款' : '付款'
              // ol.children = null
            })
          } else {
            return false
          }
        })
      } else {
        return false
      }
    })
    return list
  }

  const getLongOrdrList = () => {
    return new Promise((resolve) => {
      getLongOrderFeeDetail({ id: props.orderId }).then((res) => {
        feeDetail.value = res.result
        const result = res.result
        var data1 = []
        var dataOne = []
        if (result.orderFeeList && result.orderFeeList.length) {
          result.orderFeeList.forEach((i) => {
            if (
              (queryParam.feeType == undefined || queryParam.feeType === i.feeType) &&
              (queryParam.costType == undefined || queryParam.costType === i.costType) &&
              (queryParam.feeStatus == undefined || queryParam.feeStatus === i.feeStatus)
            ) {
              dataOne.push(i)
            }
          })
        }
        var data1 = tabletolist(dataOne) //表
        var data2 = []
        // 违章数据处理push
        if (result.violationFeeList && result.violationFeeList.length > 0) {
          var dataTwo = []
          result.violationFeeList.forEach((i) => {
            // costType转换changeCostType 匹配订单费
            if (i.costType == 0) {
              i.changeCostType = 10
            }
            if (i.costType == 1) {
              i.changeCostType = 20
            }
            // feeStatus转换changeFeeStatus 匹配订单费
            if (i.feeStatus == 0) {
              i.changeFeeStatus = 3
            }
            if (i.feeStatus == 1) {
              i.changeFeeStatus = 4
            }
            if (i.feeStatus == 2) {
              i.changeFeeStatus = 2
            }
            if (i.feeStatus == 3) {
              i.changeFeeStatus = 1
            }
            if (i.feeStatus == 5) {
              i.changeFeeStatus = 5
            }
            if (i.feeStatus == 9) {
              i.changeFeeStatus = 9
            }
            // 违章费筛选匹配
            if (
              (queryParam.feeType == undefined || queryParam.feeType === i.feeType) &&
              (queryParam.costType == undefined || queryParam.costType === i.changeCostType) &&
              (queryParam.feeStatus == undefined || queryParam.feeStatus === i.changeFeeStatus)
            ) {
              dataTwo.push(i)
            }
          })
          data2 = violationtilist(dataTwo)
        }

        totalDetailList.value = result.totalDetailList || []

        setTimeout(() => {
          tableCompulsory.dataList = data1.concat(data2)
          resolve(tableCompulsory.dataList)
        }, 0)
      })
    })
  }

  const loadCompulsoryData = () => {
    expensesKeys.value = []
    tableCompulsory.tableLoading = true

    getLongOrdrList()
      .then((data) => {
        console.log('tableCompulsory', data)
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }

  const violationtilist = (list) => {
    list.forEach((el) => {
      el.mtype = 'MENU'
      el.level = 1
      el.totalAmount = el.totalAmount
      el.toBeSettled = el.outstandingAmount //待结金额
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
          pl.feeTypeName = pl.feeTypeName
          pl.costTypeName = pl.costTypeName
        })
      } else {
        return false
      }
    })
    return list
  }

  // table 配置
  const tableCompulsory = useTable({
    pagination: false,
    columns: [
      { title: ' ', slotName: 'selectkey', width: 80, fixed: 'left' },
      { title: '费用名称', dataIndex: 'feeName', slotName: 'feeNameSort', width: 220, fixed: 'left' },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 120 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 120 },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元', width: 120 },
      { title: '实结金额', dataIndex: 'payAmount', unit: '元', width: 120 },
      { title: '待结金额', dataIndex: 'toBeSettled', unit: '元', width: 120 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 90 },
      { title: '生成时间', slotName: 'createTime', width: 180 },
      {
        title: '应结时间',
        slotName: 'receivableTime',
        width: 180,
        titleTooltipContent: '取自账单计划每期应收款日',
      },
      { title: '收支方式', dataIndex: 'payTypeName', width: 90 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 90 },
      { title: '收付款时间', dataIndex: 'payTime', width: 180 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 180 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 120 },
      { title: '费用备注', dataIndex: 'remark', width: 120, ellipsis: true },
      { title: '结算备注', dataIndex: 'settlementRemark', width: 120, ellipsis: true },
    ],
    operates: [
      {
        label: '确认收款',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) =>
          record.level == 1 &&
          record.feeType == 1 &&
          record.costType == 10 &&
          (record.refId == null || !(record.feeNameId == 7 && record.refId != null)) &&
          (record.feeStatus == 5 || record.feeStatus == 1) &&
          record.feeNameId != 55 &&
          record.feeNameId != 551,
        method: (record) => {
          orderfeepage.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        label: '确认付款',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) =>
          record.level == 1 &&
          record.feeType == 1 &&
          record.costType == 20 &&
          (record.refId == null || !(record.feeNameId == 7 && record.refId != null)) &&
          (record.feeStatus == 5 || record.feeStatus == 3) &&
          record.feeNameId != 55 &&
          record.feeNameId != 551,
        method: (record) => {
          orderfeepage.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        label: '修改费用',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) =>
          record.level == 1 &&
          record.createNode != 0 &&
          (record.feeStatus == 5 || record.feeStatus == 3 || record.feeStatus == 1) &&
          record.canModify != 0 &&
          record.feeNameId != 55 &&
          record.feeNameId != 551,
        method: (record) => {
          editFeeModalRef.value.open(record.paymentWay, record.id)
        },
      },
      // 违章按钮
      {
        label: '确认收款',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) => record.level == 1 && record.ifCanConfirm == true && record.costType == 0,
        method: (record) => {
          feepage.value.show(JSON.stringify([record.id]), { ...record, orderType: 3 })
        },
      },
      {
        label: '确认付款',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) => record.level == 1 && record.ifCanConfirm == true && record.costType == 1,
        method: (record) => {
          feepage.value.show(JSON.stringify([record.id]), { ...record, orderType: 3 })
        },
      },
      {
        label: '修改费用',
        permission: 'svms:order:long-order.confirmfee',
        show: (record) => record.level == 1 && (record.feeNameId == 55 || record.feeNameId == 551) && record.canModify == 1,
        method: (record) => {
          violationEditFee.value.show(record.id, record)
        },
      },
      // ---------
      {
        label: '收款码',
        permission: 'svms:order:long-order.qrcode',
        show: (record) => record.level == 1 && record.feeStatus == 6,
        method: (record) => {
          console.log('收款码', record)

          qrcodeFrom.value = 'longOrderQRCode'
          qcodeTitle.value = '收款码'
          clickRecord.value = {
            ...record,
            bizType: record.feeNameId == 55 || record.feeNameId == 551 ? 3 : 2,
            refId: record.feeNameId == 55 || record.feeNameId == 551 ? record.businesId : record.orderId,
          }
          payQCodeModal.value = true
        },
      },
      {
        label: '取消收款',
        permission: 'svms:order:long-order.qrcodeCancel',
        show: (record) => record.level == 1 && record.feeStatus == 6,
        method: (record) => {
          console.log('取消收款', record)

          qrcodeFrom.value = 'longOrderQRCodeCancel'
          qcodeTitle.value = '取消收款'
          clickRecord.value = {
            ...record,
            bizType: record.feeNameId == 55 || record.feeNameId == 551 ? 3 : 2,
            refId: record.feeNameId == 55 || record.feeNameId == 551 ? record.businesId : record.orderId,
          }
          payQCodeModal.value = true
        },
      },
    ],
  })

  // 合并确认
  const expenses = () => {
    if (expensesKeys.value.length == 0) {
      Message.error('请选择费用项')
      return false
    }
    checkManyToConfirm({ idList: expensesKeys.value }).then((res) => {
      if (res.code == 200) {
        orderfeepage.value.show(JSON.stringify(expensesKeys.value), { orderId: props.orderId })
      } else {
        Message.error(res.message)
        return false
      }
    })
  }

  const qcodeConfirm = (details) => {
    qcodeCfLoading.value = true

    cancelPay({ id: details.id })
      .then(() => {
        Message.success('取消收款成功')
        payQCodeModal.value = false
      })
      .finally(() => {
        qcodeCfLoading.value = false
      })
  }

  const payQCodeClose = () => {
    tableCompulsory.tableLoading = true
    setTimeout(() => {
      console.log('3s close')
      loadCompulsoryData()
    }, 3000)
  }

  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    expensesKeys.value = []
    loadCompulsoryData()
  }

  onMounted(() => {
    loadCompulsoryData()
  })
</script>

<style lang="less" scoped>
  .menus {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
    .menus-item {
      color: #4e5969;
      font-size: 28rpx;
      padding: 5px 16px;
      margin-right: 12px;
      font-weight: 400;
      cursor: pointer;
    }
    .active {
      border-radius: 30px;
      color: #1890ff;
      font-weight: 500;
      background: #f2f3f5;
    }
  }

  .check-box {
    margin-top: 4px;
  }
  .transform-top {
    margin-top: -30px;
  }
  .cost-button {
    text-align: right;
    div {
      display: inline-block;
      background: #1890ff;
      color: #fff;
      font-size: 14px;
      border-radius: 2px;
      padding: 4px 10px;
      margin-bottom: 20px;
      cursor: pointer;
    }
  }
  // .hide-card-title {
  :deep(.arco-card-header) {
    display: none;
  }
  // }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-td-content:empty::before) {
    content: ' ';
  }
</style>
